package com.example.lycdays.ui.detail;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lycdays.BaseApplication;
import com.example.lycdays.R;
import com.example.lycdays.data.bean.Event;
import com.example.lycdays.data.bean.User;
import com.example.lycdays.data.repositiory.EventDataBase;
import com.example.lycdays.ui.change.ChangeActivity;
import com.example.lycdays.util.TimeTool;
import com.google.gson.Gson;

import org.litepal.LitePal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DetailActivity extends AppCompatActivity {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final String TAG = "myTag";
    private String URL;

    TextView textViewEventName, textViewEventGap, textViewEventDate, textViewEventNote;
    Button buttonDelete, buttonUpdate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        Toolbar toolbar = findViewById(R.id.toolbarLogin);
        toolbar.setTitle("详情");
        toolbar.setTitleTextColor(getColor(R.color.colorWhite));
        setSupportActionBar(toolbar);

        textViewEventName = findViewById(R.id.textViewDetailName);
        textViewEventGap = findViewById(R.id.textViewDetailGap);
        textViewEventDate = findViewById(R.id.textViewDetailDate);
        textViewEventNote = findViewById(R.id.textViewDetailNote);
        URL = getString(R.string.URL);

        final Event event = (Event) getIntent().getSerializableExtra("event");
        //Toast.makeText(DetailActivity.this, event.getEventName(), Toast.LENGTH_LONG).show();

        textViewEventName.setText(event.getEventName());

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = format.format(new Date());
        int eventGap = TimeTool.caculateDate(nowDate, event.getEventDate());
        String eventGapStr = null;
        if (eventGap > 0) {
            eventGapStr = "已经" + eventGap + "天";
        } else if (eventGap < 0) {
            eventGapStr = "还有" + -eventGap + "天";
        } else {
            eventGapStr = "就在今天";
        }
        textViewEventGap.setText(eventGapStr);
        textViewEventDate.setText(event.getEventDate());
        textViewEventNote.setText(event.getEventNotes() == null ? "" : event.getEventNotes());



        buttonUpdate = findViewById(R.id.buttonDetailUpdate);
        buttonDelete = findViewById(R.id.buttonDetailDelete);

        buttonUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DetailActivity.this, ChangeActivity.class);
                intent.putExtra("event", event);
                startActivity(intent);

            }
        });

        buttonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //    通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象
                AlertDialog.Builder builder = new AlertDialog.Builder(DetailActivity.this);
                //    设置Title的图标
                builder.setIcon(R.drawable.ic_error_blue_24dp);
                //    设置Title的内容
                builder.setTitle("警告");
                //    设置Content来显示一个信息
                builder.setMessage("确定删除吗？");
                //    设置一个PositiveButton
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                        EventDataBase.deleteEvent(event);

                        if(BaseApplication.isIsRegister()) {
                            try {
                                String userName = LitePal.findFirst(User.class).getUserName();
                                long createTime = event.getCreateTime();

                                Gson gson = new Gson();
                                HashMap<String, Object> param = new HashMap<>();
                                param.put("userName", userName);
                                param.put("createTime", createTime);
                                deleteWithOkhttp(gson.toJson(param));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        Toast.makeText(DetailActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
                //    设置一个NegativeButton
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        //Toast.makeText(DetailActivity.this, "negative: " + which, Toast.LENGTH_SHORT).show();

                    }
                });
                //    显示出该对话框
                builder.show();
            }
        });
    }

    private void deleteWithOkhttp(final String param) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = RequestBody.create(JSON, param);
                    Request request = new Request.Builder()
                            .post(requestBody)
                            .url("http://" + URL + "/event/delete")
                            .build();

                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.d(TAG, "data" + responseData);
                    //handleBackUpResult(responseData);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    @Override
    protected void onPause() {
        super.onPause();
        this.finish();
    }
}
